package com.zmx.b2c.stock.service;

import com.nepxion.aquarius.cache.annotation.CacheEvict;
import com.nepxion.aquarius.cache.annotation.Cacheable;
import com.zmx.b2c.stock.dto.ProductStockDto;
import com.zmx.b2c.stock.entity.ProductStock;
import com.zmx.b2c.stock.repository.ProductStockRepository;
import com.zmx.b2c.stock.service.mapper.ProductStockMapper;
import com.zmx.common.common.contents.cache.Expire;
import com.zmx.common.common.contents.cache.ProductCacheConstents;
import com.zmx.common.common.exception.BusinessException;
import com.zmx.common.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
@author zhaomxr
*/
@Service
public class ProductStockService extends BaseService<ProductStock, ProductStockDto, ProductStockRepository, ProductStockMapper>  {

    /**
     * 根据商品id查询商品库存
     * @param productId
     * @return
     */
    @Cacheable(name = ProductCacheConstents.PRODUCT_STOCK, key = "#productId", expire = Expire.MINUTE_30)
    public ProductStockDto getByProductId(Long productId) {
        ProductStock productStock = repository.findByProductId(productId);
        return entityToDto(productStock);
    }

    /**
     * 根据商品id批量查询商品库存
     * @param productIds
     * @return
     */
    public List<ProductStockDto> getByProductIdIn(Long[] productIds) {
        return entityToDto(repository.findByProductIdIn(productIds));
    }

    /**
     * 更新库存
     * @param quantity
     * @param productId
     */
    @CacheEvict(name = ProductCacheConstents.PRODUCT_STOCK, key = "#productId")
    public void updateStock(int quantity, Long productId) {
        if (quantity <= 0) {
            throw new BusinessException("error updateStock quantity must > 0");
        }
        repository.updateStock(quantity, productId);
    }
}
